package main

import (
	"runtime"
	"log"
	"os"
	"io/ioutil"
	"encoding/json"
	"time"
	"crypto/md5"
	"encoding/hex"
)

type Config struct {
	Mysql struct{
		Host string
		Username string
		Password string
		Dbname string
		Charset string
	}
}

var DockerId string

var (
	salt = "51talk"
)

func main() {
	//获取docker_id
	DockerId = getDockerId()
	//使用上多核
	runtime.GOMAXPROCS(runtime.NumCPU())
	//工作
	DoTask()
	os.Getpid()
}

//获取docker_id
func getDockerId() (string) {
	//TODO
	return "1"
}

//数据库配置信息
func GetConfig() Config {
	config_json, _ := ioutil.ReadFile("/home/www/goapk/src/amqp/db_config.json")
	var config Config
	json.Unmarshal([]byte(config_json), &config)
	return config
}

func DoTask() {
	runTaskList := make(map[string]map[string]string)

	for{
		doTaskList := make(map[string]map[string]string)

		allTaskList := getTaskList()

		for _,task := range allTaskList{
			_, ok := runTaskList[task["id"]]
			if(false == ok){
				doTaskList[task["id"]] = allTaskList[task["id"]]
			}
		}

		for _,task := range doTaskList{
			go runTask(task)
			runTaskList[task["id"]] = task
		}

		time.Sleep(5*time.Second)
	}

}

//并发执行连接
func runTask(task map[string]string) {
	//获取Uri
	uri := getAmqpUriString()
	//获取交换机类型
	exType := getExchangeType(task)

	//调用消费者
	c, err := NewConsumer(uri, task["exchange"], exType, task["queue"], task["route_key"], "simple-tag",task["id"])

	if err != nil {
		log.Fatalf("%s", err)
	}

	log.Printf("running forever")
	select {}

	log.Printf("shutting down")

	if err := c.Shutdown(); err != nil {
		log.Fatalf("error during shutdown: %s", err)
	}
}

//获取URI
func getAmqpUriString () string {
	/*userName := task["user_name"]
	passWord := task["password"]
	hostUri := task["connect"]

	amqpString := "amqp://" + userName + ":" + passWord + "@" + hostUri + "/"
	return amqpString*/
	return "amqp://admin:123456@172.16.0.221:5672/"
}


//获取交换机类型
func getExchangeType (task map[string]string) string {
	var exchangeType string

	if task["type"] == "1" {
		exchangeType = "fanout"
	} else if task["type"] == "2" {
		exchangeType = "direct"
	} else if task["type"] == "3" {
		exchangeType = "topic"
	}
	return exchangeType
}

//拼接调用API接口地址
func getJoinApiUrl (api_url string,params string) (string) {

	var dat map[string]interface{}

	if err := json.Unmarshal([]byte(params), &dat); err != nil {
		return api_url
	}

	paramsStr := ""
	id := 1
	for key,_ := range dat {
		//如果有整型不处理
		_,ok := dat[key].(string)
		if ok != true {
			paramsStr += ""
			break;
		}
		if id == 1 {
			paramsStr += string("?") + string(key) + "=" + dat[key].(string)
		} else {
			paramsStr += string("&") + string(key) + "=" + dat[key].(string)
		}
		id++
	}

	//加密
	sign := ""
	if params != "" && paramsStr != "" {
		sign = string("&sign=") + string(createAccessSign(string(params) + string(salt)))
	}

	return string(api_url) + string(paramsStr) + string(sign)
}

//创建秘钥
func createAccessSign(params string) string {
	md5Ctx := md5.New()
	md5Ctx.Write([]byte(params))
	cipherStr := md5Ctx.Sum(nil)
	return string(hex.EncodeToString(cipherStr))
}
